{% extends "home/layout.html" %}
{% block title %}Home<-{{ super() }}{% endblock %}
{% block head %}
    {{ super() }}
    <style type="text/css">
        #edit-area,
        #btn-area {
            position: relative;
        }
        #container,
        #preview {
            position: absolute;
            width: 450px;
            height: 250px;
            border: 1px solid grey;
        }
        #preview > iframe {
            width: 440px;
            height: 240px;
        }
        #preview {
            left: 460px;
            overflow-y: scroll;
        }
        #btn-area {
            top: 260px;
        }
        #btn-area > button {
            position: absolute;
        }
        #btn-parse,
        #btn-save {
            font-size: 18px;
            padding: 5px;
        }

        #btn-parse {
            left: 300px;
        }

        #btn-save {
            left: 380px;
        }

        .monaco-editor.vs .token.custom-info {
            color: grey;
        }
        .monaco-editor.vs .token.custom-error {
            color: red;
            font-weight: bold;
            font-size: 1.2em;
        }
        .monaco-editor.vs .token.custom-notice {
            color: orange;
        }
        .monaco-editor.vs .token.custom-date {
            color: green;
        }

        .monaco-editor.vs .token.custom-raw-text {
            color: #fa1;
            font-weight: 900;
            font-size: 1.2em;
        }
    </style>
    <script type="text/javascript">
        if(!window.GLOBAL) {
          window.GLOBAL = {};
        }
        window.GLOBAL.IS_ADMIN = "{{ is_admin }}".toLowerCase() == 'true' ? true : false;
    </script>
{% endblock %}
{% block content %}
    {{ super() }}
    <script type="text/plain" id="test-content">{{ content | safe }}</script>
    <div id="edit-area">
        <div id="container"></div>
        <!-- <div id="preview"></div> -->
        <iframe id="preview" src="data:text/html;charset=utf-8,"></iframe>
    </div>
    <div id="btn-area">
        <button id="btn-parse">解析</button>
        <button id="btn-save">保存</button>
    </div>
{% endblock %}
{% block js_import %}
    {{ super() }}
    <script type="text/javascript" src="{{ url_for('static', filename='node_modules/monaco-editor/min/vs/loader.js') }}"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        require.config({
            paths: {
                'vs': "{{ url_for('static', filename='node_modules/monaco-editor/min/vs') }}"
            }
        });
        require(['vs/editor/editor.main'], function() {

            var language_name = 'RichMarkup';

            monaco.languages.register({
                id: language_name
            });
            // demo: https://microsoft.github.io/monaco-editor/monarch.html
            // how defined: https://github.com/Microsoft/monaco-editor/blob/master/website/playground/monaco.d.ts.txt
            monaco.languages.setMonarchTokensProvider(language_name, {
                tokenizer: {
                    root: [
                        [/\[error.*/, "custom-error"],
                        [/^@\w+\:\s+\S+/, "custom-notice"],
                        [/\[info.*/, "custom-info"],
                        [/\[[a-zA-Z 0-9:]+\]/, "custom-date"],
                        [/((?=[^\\])'{3})(.|\s)+?((?=[^\\])'{3})/, "custom-raw-text"]
                    ]
                }
            });
            // https://github.com/Microsoft/monaco-editor/blob/master/website/playground/playground.mdoc
            monaco.languages.registerCompletionItemProvider(language_name, {
                provideCompletionItems: function() {
                    return [{# don not escape with jinja2 template #}{% raw %}
                        {
                            label: 'raw_html',
                            kind: monaco.languages.CompletionItemKind.Text,
                            insertText: '"""{{raw_html}}"""'
                        },
                        {
                            label: 'raw_text',
                            kind: monaco.languages.CompletionItemKind.Text,
                            insertText: "'''{{raw_text}}'''"
                        },
                        {
                            label: 'code',
                            kind: monaco.languages.CompletionItemKind.Keyword,
                            insertText: '```+{{language}}\n{{code}}\n```'
                        },
                        {
                            label: 'tag',
                            kind: monaco.languages.CompletionItemKind.Snippet,
                            insertText: [
                                '<{{tag}}>',
                                    '\t{{content}}',
                                '</{{tag}}>'
                            ].join('\n'),
                            documentation: 'Raw Html Block'
                        }
                    {% endraw %}];
                }
            });

            function getCode() {
                /*
                return [
                    '@hello: world',
                    '',
                    "'''hello world!'''",
                    '',
                    '```+python',
                    'import os',
                    '',
                    'def func():',
                    '   def ff():',
                    '       pass',
                    "       return ''",
                    '',
                    '   return {',
                    "       k: 'v'",
                    '   }',
                    '',
                    'os.system("pwd")',
                    '```'
                ].join('\n');
                */
                return document.querySelector('#test-content').innerHTML;
            }
            var container = document.getElementById('container');
            // cofiguration: https://code.visualstudio.com/docs/customization/userandworkspace#_default-settings
            var editor = monaco.editor.create(container, {
                value: getCode(),
                language: language_name,
                quickSuggestionsDelay: 2,
                renderIndentGuides: true,
                fontLigatures: true,
                locale:"zh-CN", // https://code.visualstudio.com/docs/customization/locales
                fontSize: 16
            });

            $('#btn-parse').on('click', function() {
                var _val = editor.getValue();
                $.ajax({
                    url: '/',
                    type: 'POST',
                    dataType: 'html',
                    data: {
                        content: _val
                    },
                    success: function(result) {
                        // http://stackoverflow.com/questions/8240101/set-content-of-iframe
                        $('#preview').attr('src', 'data:text/html;charset=utf-8,' + escape(result));
                    },
                    error: function(msg) {
                        if(msg && (typeof msg == 'object' && 'statusText' in msg)) {
                            msg = msg.statusText;
                        }
                        $('#preview').attr('src', 'data:text/html;charset=utf-8,' + escape(msg));
                    }
                })
            })
        });
    });
    </script>
{% endblock %}